package com.fz.song.web.controller;

import cn.hutool.core.util.IdUtil;
import com.fz.song.framework.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 77088
 * @title: TokenController
 * @projectName idempotent-demo
 * @description: TODO
 * @date 2021/11/119:04
 */
@Api(tags = "幂等性demo-token防止重复提交")
@Slf4j
@RestController
@RequestMapping("idempotent")
public class TokenController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @ApiOperation(value = "获取token", notes = "防止前端重复提交,先获取一个token,再提交的时候需要带上token值")
    @GetMapping("getToken")
    public R getToken() {
        String token = IdUtil.simpleUUID();
        redisTemplate.opsForValue().set(token, "1", 1, TimeUnit.DAYS);
        return R.ok("获取token", token);
    }

    @ApiOperation(value = "提交信息", notes = "接收到信息后,执行删除token,删除成功才操作,不然跳过操作")
    @GetMapping("submit")
    public R submit(String token) {
        boolean delete = redisTemplate.delete(token);
        if (!delete) {
            log.warn("删除token异常,跳过操作");
            return R.ok("提交数据", true);
        }
        log.info("业务操作");
        return R.ok("提交数据", true);
    }
}
